package com.zzs.esp.service;

import com.zzs.esp.dao.UserMapperDao;
import com.zzs.esp.entity.Role;
import com.zzs.esp.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author ZechariahZheng
 * @Date 2021/1/26 10:38
 * @Version 1.0
 * @description
 */
@Service
public class UserService implements UserDetailsService {
    @Autowired
    private UserMapperDao userMapperDao;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userMapperDao.loadUserByUsername(s);
        if (user == null) {
            throw new UsernameNotFoundException("账号不存在");
        }
        //测试数据库用户密码未加密，这里手动设置
        System.out.println(user.getPassword());
        String encodePassword = passwordEncoder.encode(user.getPassword());
        System.out.println("加密后的密码："+encodePassword);
        user.setPassword(encodePassword);
        List<Role> userRoles = userMapperDao.getUserRolesByUid(user.getId());
        user.setUserRoles(userRoles);
        user.setUserName(s);
        return user;
    }
}
